package main

// 业务编程流程 main => middlewares => defs(message,err)
// =>handlers =>dbops => response

import (
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
)

type middleWareHandler struct {
	r *httprouter.Router
}

func NewMiddleWareHandler(r *httprouter.Router) http.Handler {
	m := middleWareHandler{}
	m.r = r
	return m
}

// 劫持这个方法来实现http.Handler接口
func (m middleWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// check session
	ValidateUserSession(r)
	m.r.ServeHTTP(w, r)

}

func RegisterHandlers() *httprouter.Router {
	router := httprouter.New()
	router.POST("/user", CreateUser)       // 注册用户
	router.POST("/user/:user_name", Login) // 用户登陆
	return router
}

/*
	整个程序的处理逻辑：
	main => handler => validations => business logic => response
	其中validations部分：
	1)request校验
	2)user相关校验
	business logic处理部分：
	1)data model相关处理
	2)error处理
*/
func main() {
	//router := httprouter.New()
	// 注册路由对象
	//router := RegisterRouter()
	router := RegisterHandlers()
	mh := NewMiddleWareHandler(router)
	log.Fatal(http.ListenAndServe(":9002", mh))
}
